<template>
  <div>
    <tool-bar nav="" title='mybatisLog、Myoql 提取Sql'></tool-bar>
    <kv label="log">
      <el-input type="textarea" v-model="$data.txt1" :rows="6"></el-input>
    </kv>

    <kv label="提取Sql">
      <el-button @click="exec_click">执行⤵</el-button>
    </kv>

    <kv label="Sql">
      <el-input type="textarea" v-model="$data.txt2" :rows="16"></el-input>
    </kv>

  </div>
</template>
<script setup>
/**
 * Created by CodeGenerator
 */

import {format} from 'sql-formatter';

defineOptions({
  name: "query-json",
  inheritAttrs: true,
});

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();


//定义data
const $data = reactive({"txt1": "", "txt2": "", "defValue": false, "nullable": true, "embed": []});


const $props = defineProps({});


const list = ref();

//定义事件
const $emit = defineEmits(["update:modelValue", "loaded"]);

const getMybatisSql = txt => {

  var lines = txt.replaceAll("\r\n", "\n")
      .replaceAll("\r", "\n")
      .split("\n");

  var sql = "", ps = "";
  lines.forEach(line => {
    if (sql && ps) {
      return;
    }

    var index = line.indexOf("==> ");
    if (index === 0) {
      line = line.slice(index + 4).trim()
    }

    if (line.startsWith("Preparing:")) {
      sql = line.slice("Preparing:".length)
    } else if (line.startsWith("Parameters:")) {
      ps = line.slice("Parameters:".length)
    }
  });


  if (!sql) {
    return "";
  }


  ps = ps.split(",").map(it => it.trim()).filter(it => it);

  var getPv = index => {
    var s = ps[index];
    if (!s) return "null";

    var i = s.lastIndexOf("(");
    var v = s.slice(0, i);
    var type = s.slice(i + 1, -1);
    if (["String", "LocalDateTime", "LocalDate", "LocalTime", "Date"].includes(type)) {
      return "'" + v + "'"
    }
    return v;
  }

  var i = 0;
  return sql.replace(/(\?)/g, m => getPv(i++))
}

const getMyOqlSql = txt => {
  var lines = txt.split("\n");

  var pIndex = lines.findIndex(it => it.startsWith("[参数] "));
  if (pIndex < 0) {
    return "";
  }

  var pl = lines.splice(pIndex, 1)[0];
  pl = pl.slice("[参数] ".length)

  const isInsert = lines[0].includes("[插入]")
  lines[0] = lines[0].replace("[select]", "").replace("[查询]", "").replace("[插入]", "").trim()
  var sql = lines.join("\n");

  var plJson = JSON.parse(pl);
  if (plJson.getJsType() == "array") {
    sql += "\n\n不识别Array的Json!"
    return sql;
  }
  Object.keys(plJson).forEach(key => {
    var value = plJson[key];
    var reg = RegExp(`:${key}\\b`, "g");
    if (jv.isNull(value)) {
      sql = sql.replaceAll(reg, "null");
    } else if (value.getJsType() == "string") {
      sql = sql.replaceAll(reg, `'${value}'`);
    } else {
      sql = sql.replaceAll(reg, value);
    }
  })
  return sql;
}

const exec_click = function () {
  $data.txt2 = "";
  jv.$saveData("txt1", $data.txt1);

  var txt = getMybatisSql($data.txt1);
  if (!txt) {
    txt = getMyOqlSql($data.txt1);
  }

  if (!txt) {
    $data.txt2 = "非法格式！"
  }

  $data.txt2 = txt

  try {
    $data.txt2 = format($data.txt2, {language: 'mysql'});
  } catch (e) {
    console.error(e)
  }
};


onMounted(function () {
  jv.$loadData("txt1", v => $data.txt1 = v);
});

</script>

<style lang="scss" scoped>
::v-deep(.kv>.k) {
  flex: 1;
}

::v-deep(.kv>.v>:first-child) {
  max-width: unset;
}

.grid {
  position: relative;
  margin-left: 20px !important;
  margin-top: 20px !important;


  ::v-deep(textarea), ::v-deep(.el-col), ::v-deep(.el-textarea) {
    height: 100%;
  }
}

.op_column {
  padding-top: 150px;
  padding-bottom: 150px;
  display: flex;
  flex-wrap: wrap;
  place-content: center;
  align-content: space-around;
  position: relative;
  height: 100%;


  button {
    display: block;
    margin: 10px 6px;
  }

}
</style>